/**
 * @公司名称: 上海恒生聚源数据服务有限公司
 * @部门    ：产品开发三部
 * @工程名  : UDEP
 */
package org.jony.JProject.objectPool;


/**
 * @类说明:
 * @作者 ：Jony
 * @E-mail : lij@gildata.com
 * @创建日期: 2011-8-22上午9:03:14
 * @版本号 ：V.1.0
 */
public class TestGeneralObjectPool implements Runnable {

	private static ObjectPool pool;

	/**
	 * @功能介绍：
	 * @创建时间：2011-8-22上午9:03:14 by Jony
	 * @param args
	 */
	public static void main(String[] args) {

		System.out.println("创建对象池");
		// 创建对象池工厂
		ObjectPoolFactory poolFactory = ObjectPoolFactory.getInstance();

		// 定义所创建对象池的属性
		ParameterObject paraObj = new ParameterObject(1, 1);

		// 利用对象池工厂,创建一个存放StringBuffer类型对象的对象池
		pool = poolFactory.createPool(paraObj, StringBuffer.class);
		// TODO: this pool should be stored in cache for further use

		// 编写几个独立的线程去借出使用并归还对象
		System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
		TestGeneralObjectPool test = new TestGeneralObjectPool();
		Thread thread1 = new Thread(test);
		Thread thread2 = new Thread(test);
		Thread thread3 = new Thread(test);
		thread1.start();
		thread2.start();
		thread3.start();
		System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
	}

	public void run() {
		System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().getName() + "尝试借出对象");
			StringBuffer buffer = (StringBuffer) pool.borrowObject();
			buffer.append(Thread.currentThread().getName() + ", "
					+ String.valueOf(i));
			System.out.println(buffer.toString());

			// 等待5秒然后再归还该对象到pool
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			pool.returnObject(buffer);
		}
		System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
	}
}
